package com.ziji.rocketmq.general;


import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

/**
 * 定义同步消息发送生产者
 *
 * @author <a href="mailto:ziji.zhao@aliyun.com">ziji</a>
 * @since 2021/11/12
 */
public class SyncProducer {
    public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException {
        // 创建一个 producer，参数为 Producer Group 名称
        DefaultMQProducer producer = new DefaultMQProducer("pg");
        // 指定 NameServer 地址
//        producer.setNamesrvAddr("rocketmqOS:9876");
        producer.setNamesrvAddr("localhost:9876");
        // 设置当发送失败时重试发送的次数，默认为2次
        producer.setRetryTimesWhenSendFailed(3);
        // 设置发送超时时限为5s，默认3s
        producer.setSendMsgTimeout(5000);

        // 开启生产者
        producer.start();

        // 生产并发送 100 条消息
        for (int i=0; i<10; i++) {
            byte[] body = ("Hi," + i).getBytes();
            Message msg = new Message("someTopic", "someTag", body);
//            Message msg = new Message("someTopic", "someTag" + (i % 3), body);
            // 为消息指定 key
            msg.setKeys("key-" + i);
            SendResult sendResult = producer.send(msg);
            System.out.println(sendResult);
        }
        // 关闭 producer
        producer.shutdown();
    }
}
// 7F0000011EDB18B4AAC23BDDC2F50000
// 7F0000011EF318B4AAC23BE2E9640000






































